<template>
  <div class="number-input">
    <span style="margin-right:4px">{{ label }}</span>
    <el-input
      v-model="text"
      type="text"
      :maxlength="length"
      :disabled="disabled"
      size="mini"
      :style="{width:`${width}px`}"
      clearable
      @input="handleEdit"
    />
  </div>
</template>

<script>
export default {
  name: '',
  components: {},
  props: {
    label: {
      type: String,
      default: ''
    },
    value: {
      type: [Number, String],
      default: ''
    },
    width: {
      type: String,
      default: '150'
    },
    length: {
      type: String,
      default: '30'
    },
    type: {
      type: String,
      default: 'integerIncZero'
    },
    precision: {
      type: [Number, String],
      default: '2'
    },
    disabled: {
      type: [Boolean, String],
      default: false
    }
  },
  data() {
    return {
      text: ''
    }
  },
  created() {
    this.text = this.value
  },
  mounted() {},
  methods: {
    valueChange(val) {
      this.text = val
      this.$emit('update:value', val)
    },
    handleEdit(e) {
      // /(\.\d{2})\d*/
      // const testPrecision = new RegExp('(\.\d{' + this.precision + '})')
      const testLength = new RegExp('(\\d{' + this.length + '})\\d*')
      if (this.type === 'integerIncZero') {
        let value = e.replace(/[^\d]/g, '') // 只能输入数字
        console.log(value)
        value = value.replace(/^0+(\d)/, '$1') // 第一位0开头，0后面为数字，则过滤掉，取后面的数字
        value = value.replace(testLength, '$1') // 最多保留Length位整数
        this.valueChange(value)
      } else if (this.type === 'integerExcZero') {
        let value = e.replace(/^(0+)|[^\d]+/g, '') // 以0开头或者输入非数字，会被替换成空
        value = value.replace(testLength, '$1') // 最多保留Length位整数
        this.valueChange(value)
      } else if (this.type === 'float') {
        const testPrecision = new RegExp('(\\.\\d{' + this.precision + '})\\d*')
        let value = e.replace(/[^\d.]/g, '') // 只能输入数字和.
        value = value.replace(/^\./g, '') // 第一个字符不能是.
        value = value.replace(/\.{2,}/g, '.') // 不能连续输入.
        value = value.replace(/(\.\d+)\./g, '$1') // .后面不能再输入.
        value = value.replace(/^0+(\d)/, '$1') // 第一位0开头，0后面为数字，则过滤掉，取后面的数字
        value = value.replace(testLength, '$1') // 最多保留Length位整数
        value = value.replace(testPrecision, '$1')// 最多保留Precision位小数
        this.valueChange(value)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.number-input{
  display: inline-flex;
  align-items: center;
}
</style>
